package com.fp.m7.server.auth;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

/**
 * A helper class for encoding raw passwords using the spring-autowired encoder & its salt source.
 * 
 * @author 7
 */
@Component
public class M7PasswordEncoder {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SaltSource saltSource;

    public String encodePassword(String username, String rawPassword) {
        // create an empty UserDetails object with only username set
        User user = new User(username, "", new ArrayList<GrantedAuthority>());
        return passwordEncoder.encodePassword(rawPassword, saltSource.getSalt(user));
    }

    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    public void setSaltSource(SaltSource saltSource) {
        this.saltSource = saltSource;
    }
}
